package com.javaee.web.servlet;
import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javaee.ejb.session.remote.EmployeeManagerRemote;
import com.javaee.web.HttpServletBase;
import com.javaee.web.SiteParameters;

/**
 * Servlet implementation class Authentication
 */
public class AuthenticationServlet extends HttpServletBase {
	private static final long serialVersionUID = 1L;

	@EJB
	private EmployeeManagerRemote employeeManager;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AuthenticationServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String targetPage = request.getParameter("targetPage");

		if (userName == null || targetPage == null) {
			response.sendRedirect(SiteParameters.getFullPagePath("error"));
		} else {
			currentEmployee = employeeManager.getByUserName(userName);

			if (currentEmployee == null) {
				// Echec d'authentification
				session.setAttribute("athenticationFailed", new Boolean(true));
				session.setAttribute("accessPageFailed", targetPage);
				response.sendRedirect(SiteParameters
						.getFullServletPath("index"));
			} else {
				// Authentification reussie
				session.removeAttribute("athenticationFailed");
				session.removeAttribute("accessPageFailed");
				session.setAttribute("currentEmployee", currentEmployee);
				if (currentEmployee.getIsAdmin()) {
					targetPage = SiteParameters
							.getFullServletPath("administration");
				} else {

				}
				response.sendRedirect(targetPage);
			}
		}
	}
}
